<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Commodity;
use App\Models\MachineGood;
use App\Models\Order;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;


class MachineGoodController extends Controller
{
   public function index(Content $content,$id){
        $goods = Commodity::where('status',1)->get()->toArray();
        foreach($goods as $k=>$v){
            $res = MachineGood::where('machine_id',$id)->where('good_id',$v['id'])->first();
            if($res){
                $res = $res->toArray();
                $goods[$k]['stock'] = $res['stock'];
            }else{
                $goods[$k]['stock'] = 0;
            }
        }
        return $content->view('machine_good',['goods'=>$goods,'id'=>$id]);
   }

   public function store(Request $request){
        $machine_id = $request->input('machine_id');
        $good_id = $request->input('good_id');
        $stock = $request->input('stock');
        $goods_id = MachineGood::where('machine_id',$machine_id)->get('good_id')->toArray();
        $ids = [];
        foreach($goods_id as $v){
            $ids[] = $v['good_id'];
        }
        foreach($good_id as $k=>$v){
            if(in_array($v,$ids)){
                MachineGood::where('machine_id',$machine_id)->where('good_id',$v)->update(['stock'=>$stock[$k]]);
            }else{
                $machine = new MachineGood();
                $machine->machine_id = $machine_id;
                $machine->good_id = $v;
                $machine->stock = $stock[$k];
                $machine->save();
            }
        }
        return redirect("admin/machine_good/$machine_id");
   }

   public function machineOrder(Content $content,$id){
       $order = Order::with('user')->where('machine_id',$id)->get();
       if(!$order->isEmpty()){
            $order = $order->toArray();
       }else{
           $order = [];
       }
       return $content->view('machine_order',['orders'=>$order]);
   }
}
